<%@page import="net.sf.json.JSONObject"%>
<%@page contentType="application/json; charset=UTF-8"%>
<%@ page language="java" 
	import="java.util.*,
			java.text.SimpleDateFormat,
			net.sf.json.*,
			org.hibernate.Session,
			org.hibernate.Transaction,
			org.hibernate.criterion.Restrictions,
			utilities.DateService,
			database.HibernateUtil,
			database.model.Article,
			database.model.Section"%>
 
 <%
 	Long id = new Long(request.getParameter("id"));
 	Session se = HibernateUtil.currentSession();
	Transaction trans = se.beginTransaction();
	List<Section> list =  se.createCriteria(Section.class).add(Restrictions.like("id", id)).setFetchSize(1).list();
	Section section = list.get(0);
	String ifModifiedSince = request.getHeader("If-Modified-Since");
	Date ifModifSinceDate = DateService.getIfModifiedSinceDateFromString(ifModifiedSince);
 	int statusCode = 200;
	if(ifModifSinceDate != null)
 	{
 		if(section.getLastBuildDate().compareTo(ifModifSinceDate) < 0)
 		{
 			statusCode = 304;
 		}
 	}
 	response.setHeader("Last-Modified", DateService.currentDateGMT());
 	response.setStatus(statusCode);
 	JSONObject rootJO = null;
 	if(statusCode == 200)
 	{
		List<Article> articles = section.getArticles();
		rootJO = new JSONObject();
		rootJO.put("title", section.getTitle());
		rootJO.put("description", section.getDescription());
		rootJO.put("url", section.getUrl());
		rootJO.put("pubDate",section.getPubDate());
		
		if(articles.size() > 0)
		{
			JSONArray articlesJA = new JSONArray();
			for(Article article : articles)
			{
				JSONObject articleJO = new JSONObject();
				articleJO.put("id", article.getId().toString());
				articleJO.put("title", article.getTitle());
				articleJO.put("subtitle", article.getSubtitle());
				articleJO.put("pubDate",article.getPublicationDate());
				articlesJA.add(articleJO);
			}
			rootJO.put("articles", articlesJA);
		}
 	}
	trans.commit();
	HibernateUtil.closeSession();
%>
<%= (rootJO != null ?rootJO.toString():"") %>